package com.lvyp.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvyp.server.mapper.AdminMapper;
import com.lvyp.server.mapper.MenuMapper;
import com.lvyp.server.pojo.Admin;
import com.lvyp.server.pojo.Menu;
import com.lvyp.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lvyp
 * @since 2021-04-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 根据id查询菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuByAdminId() {
        // 从security全局上下文中获取当前登录用户，再获取用户id
        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        // 创建redis操作对象
        ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
        // 从redis缓存中查询数据：menu_1 : value
        List<Menu> menus = (List<Menu>) valueOps.get("menu_" + adminId);
        System.out.println("MenuServiceImpl:menus-----"+menus);

        // 如果redis查询为空，去数据库中查询
        if (CollectionUtils.isEmpty(menus)) {
            // 数据库中查询menus
            menus = menuMapper.getMenusByAdminId(adminId);
            // 将数据添加到redis中
            valueOps.set("menu_"+adminId,menus);
        }

        return menus;
    }

    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
